<template>
  <div>
      <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 active控制激活项 -->
    <el-card>
        <el-alert title="添加商品信息" type="info" show-icon :closable="false" center></el-alert>
        <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品内容"></el-step>
            <el-step title="完成"></el-step>
        </el-steps>

        <!-- 每个表单 -->
        <el-form :model="addGoodsForm" :rules="addGoodsRules" ref="addGoodsRef" label-width="100px" label-position="top">
        <!-- tab栏区域  before-leave切换之前触发   @tab-click切换后触发  action表示图片上传的后台API地址 on-preview点击上传后的预览 on-remove处理移除图片 list-type指定渲染效果 on-success上传图片成功时调用-->
        <el-tabs :tab-position="tabPosition"  v-model="activeIndex" :before-leave="beforeLeave" @tab-click="tabClicked">
            <el-tab-pane label="基本信息" name="0">
                <el-form-item label="商品名称" prop="goods_name"><el-input v-model="addGoodsForm.goods_name"></el-input></el-form-item>
                <el-form-item label="商品价格" prop="goods_price"><el-input v-model="addGoodsForm.goods_price" type='number'></el-input></el-form-item>
                <el-form-item label="商品重量" prop="goods_name"><el-input v-model="addGoodsForm.goods_weight" type='number'></el-input></el-form-item>
                <el-form-item label="商品数量" prop="goods_number"><el-input v-model="addGoodsForm.goods_number" type='number'></el-input></el-form-item>
                <el-form-item label="商品列表" prop="goods_cat"><el-cascader v-model="addGoodsForm.goods_cat" :options="GoodsCateData" :props="cateProps" @change="addGoodsSelectHandleChange"></el-cascader></el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品参数" name="1">
                <!-- 渲染动态数据表单 -->
                <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
                    <el-checkbox-group v-model="item.attr_vals">
                        <el-checkbox :label="a" v-for="(a,b) in item.attr_vals" :key="b"></el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品属性" name="2">
                <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
                    <el-input v-model="item.attr_vals"></el-input>
                </el-form-item>
            </el-tab-pane>          
            <el-tab-pane label="商品图片" name="3">
                <el-upload class="upload-demo" :action="upLoadUrl" :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture" :headers="headerObj" :on-success="successUpload">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
            </el-tab-pane>
            <el-tab-pane label="商品内容" name="4">
                <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
                <el-button type="primary" @click="AddGoods">添加商品</el-button>
            </el-tab-pane>
        </el-tabs>
        </el-form>

        <!-- 预览对话框 -->
        <el-dialog title="图片预览" :visible.sync="previewDialogVisible" width="50%" >
            <img :src="previewPath" alt="" class="previewImg">
        </el-dialog>
        
    </el-card>
  </div>
</template>
<script>
import _ from 'lodash'
export default {
    data() {
        return {
          activeIndex:'0',
          tabPosition:'left',
          addGoodsForm:{  
              goods_name:'',
              goods_price:0,
              goods_weight:0,
              goods_number:0,
              goods_cat:[],      //商品分类所属的数组
              pics:[], //图片的数组
              goods_introduce:'', //商品的详情

              attrs:[]  //
          },      
          addGoodsRules:{
              goods_name:[{required:true,message:'请输入正确商品名称',trigger:'blur'}],
              goods_price:[{required:true,message:'请输入正确商品价格',trigger:'blur'}],
              goods_weight:[{required:true,message:'请输入正确商品重量',trigger:'blur'}],
              goods_number:[{required:true,message:'请输入正确商品数量',trigger:'blur'}],
              goods_cat:[{required:true,message:'请选择商品分类',trigger:'blur'}],
          },
          GoodsCateData:[],  //所有商品分类数据
          cateProps:{
              label:'cat_name',
              value:'cat_id',
              children:'children'
          },    
          manyTableData:[],   //动态参数列表数据
          onlyTableData:[],    //静态参数列表数据

          upLoadUrl:'http://127.0.0.1:8888/api/private/v1/upLoad',
          headerObj:{
              Authorization:window.sessionStorage.getItem('token')             
          },
          previewPath:'',   //文件的临时地址
          previewDialogVisible:false,

          
          


        }
    },
    created() {
        this.getGoodsCateData()
    },
    methods: {
        //获取所有商品分类数据
        async getGoodsCateData(){
            const {data:res}=await this.$http.get('categories')
            if(res.meta.status!==200){
                return this.$message.error('获取商品分类数据失败');
            }
            this.GoodsCateData=res.data
            // console.log('获取商品列表数据',res.data)
      
        },

        //监听级联选择器选中变化
        addGoodsSelectHandleChange(){
            if(this.addGoodsForm.goods_cat.length!==3){
                this.addGoodsForm.goods_cat=[]
                return
            }
            // console.log('AddGoods级联选择框',this.addGoodsForm.goods_cat)
        },
        //当切换商品信息之前触发
        beforeLeave(activeName,oldActiveName){
            if(oldActiveName==='0'&&this.addGoodsForm.goods_cat.length!==3){
                this.$message.error('您有东西没有填完')
                return false
            }
        },
        //切换到商品参数
        async tabClicked(){
            if(this.activeIndex==='1'){
                const {data:res}=await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel:'many'}})
                if(res.meta.status!==200){
                    return this.$message.error('获取动态数据失败！')
                }
                res.data.forEach(item => {
                    item.attr_vals=item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
                });
                this.manyTableData=res.data
            console.log('获取动态数据数据',res.data)
            }else if(this.activeIndex==='2'){
                const {data:res}=await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel:'only'}})
                if(res.meta.status!==200){
                    return this.$message.error('获取静态数据失败！')
                }
                
                this.onlyTableData=res.data
            // console.log('获取静态数据数据',res.data)
            }
        },
        //处理图片预览效果
        handlePreview(file){
            console.log('预览',file)
            // console.log('预览图片的本地地址',this.previewPath)
            const u='http://127.0.0.1:8888'
            this.previewPath=u+'/'+file.response.data.tmp_path
            console.log('拼接地址',this.previewPath)
            this.previewDialogVisible=true
        },
        //处理移除图片的操作
        handleRemove(removeImg){
            console.log(removeImg)
            //1，获取将要删除的图片的临时路径
            const linshiUrl =removeImg.response.data.tmp_path
            // console.log('删除的临时路径',linshiUrl)
            //2，从pics数组中，找到这个图片对应的索引值
            const index =this.addGoodsForm.pics.findIndex(x=>{x.pic===linshiUrl})
            console.log(index)
            //3，调用数组的splice方法，把图片信息对象，从pics数组中移除。
            this.addGoodsForm.pics.splice(index,1)
            console.log(this.addGoodsForm)
        },
        //长传图片成功时调用
        successUpload(response){
            console.log('图片上传成功时调用',response)
            //1，拼接得到一个图片信息对象
            const picInfo ={pic:response.data.tmp_path}
            //2,将图片信息对象，push到pics数组中
            this.addGoodsForm.pics.push(picInfo)
            console.log(this.addGoodsForm)
        },
        AddGoods(){
            this.$refs.addGoodsRef.validate(async valid=>{
                if(!valid){
                    return this.$message.error('请填写必要的选中项！')
                }
                //执行添加的业务逻辑
                //将数组转为字符串，lodash  cloneDeep(obj)  深拷贝
                const form=_.cloneDeep(this.addGoodsForm)
                form.goods_cat =form.goods_cat.join(',')
                // console.log('深拷贝后的数组',form)

                //处理静态数据和动态数据
                this.manyTableData.forEach(item=>{
                    const newInfo ={attr_id:item.attr_id,  attr_value:item.attr_value.join(',')}
                    this.addGoodsForm.attrs.push(newInfo)
                })
                this.onlyTableData.forEach(item=>{
                    const newInfo ={attr_id:item.attr_id,  attr_value:item.attr_value.join(',')}
                    this.addGoodsForm.attrs.push(newInfo)

                })
                form.attrs=this.addGoodsForm.attrs
                console.log('拷贝得到的form',form)

                //发起请求添加商品，商品的名称，必须时唯一的
                const {data:res}=await this.$http.post('goods',form)
                if(res.meta.status!==201){
                    return this.$message.error('添加商品失败')
                }
                this.$message.success('添加商品成功')
                this.$router.push('/goods')
            })
        }

        
    },
    computed:{
        cateId(){
            if(this.addGoodsForm.goods_cat.length===3){
                return this.addGoodsForm.goods_cat[2]
            }
            return null
        }
    }
}
</script>

<style lang="less" scoped>
.el-steps {
    margin: 15px 0;
}
/deep/.el-step__title{
    font-size: 13px;
}
.el-checkbox{
    margin-right: 5px;
}
.previewImg{
    width: 100%;
}
.el-button--primary{
    margin-top: 10px;
}

</style>